<script setup>
import { defineEmits, defineProps, onMounted, ref, watch } from 'vue'
import SmallCard from '@/components/attendanceComponents/SmallCard.vue'
import ClockBox from '@/components/ClockBox/ClockBox.vue'
import dayjs from 'dayjs'
import { getUserProfile } from '@/api/system/user'
import { getAttendanceRecordList } from '@/api/attendance'

const props = defineProps({
  time1: String,
  time2: String,
  time3: String,
  time4: String,
  userInfo: Object,
  startDate: String,
  endDate: String,
  renCalendarCurDate: String,
})
const attendanceRecordList = ref([])
const getWeek = () => {
  let datas = dayjs().day()
  let week = ['日', '一', '二', '三', '四', '五', '六']
  return '星期' + week[datas]
}
// 新疆打卡
let userIdAttendabceArr = [82] // 罗平人id
// 郑州分公司打卡
let deptAttendabce = [8253, 6707, 6708, 8254, 6701, 6702, 6703, 6704, 8255, 8256, 8242] // 8242郑州部门id
// 郑州郑州绿地之窗景峰座1号楼打卡
let cxyuserIdAttendabceArr = [147, 106, 108, 99, 163, 97] // 郑州郑州绿地之窗景峰座1号楼打卡
let deptAttendabceZhenZhou = ref(null) // 8242郑州部门id
let userIdAttendabce = ref(null) // 用户
let time1 = ref(null)
let time2 = ref(null)
let time3 = ref(null)
let time4 = ref(null)

const timeFn = () => {
  // 新疆打卡
  if (userIdAttendabceArr.includes(userIdAttendabce.value)) {
    time1.value = dayjs().hour(8).minute(0).second(59)
    time2.value = dayjs().hour(12).minute(30).second(0)
    time3.value = dayjs().hour(14).minute(30).second(59)
    time4.value = dayjs().hour(19).minute(0).second(0)
  } else if (deptAttendabce.includes(deptAttendabceZhenZhou.value)) {
    // 郑州打卡
    if (getWeek() === '星期一') {
      time1.value = dayjs().hour(7).minute(50).second(59)
    } else {
      time1.value = dayjs().hour(8).minute(30).second(59)
    }
    time2.value = dayjs().hour(12).minute(0).second(0)
    time3.value = dayjs().hour(14).minute(0).second(59)
    time4.value = dayjs().hour(18).minute(30).second(0)
  } else if (cxyuserIdAttendabceArr.includes(deptAttendabceZhenZhou.value)) {
    // 郑州打卡
    if (getWeek() === '星期一') {
      time1.value = dayjs().hour(7).minute(50).second(59)
    } else {
      time1.value = dayjs().hour(9).minute(0).second(59)
    }
    time2.value = dayjs().hour(12).minute(0).second(0)
    time3.value = dayjs().hour(14).minute(0).second(59)
    time4.value = dayjs().hour(19).minute(0).second(0)
  } else {
    //上下班打卡时间
    if (getWeek() === '星期一') {
      time1.value = dayjs().hour(7).minute(50).second(59)
    } else {
      time1.value = dayjs().hour(8).minute(0).second(59)
    }
    time2.value = dayjs().hour(12).minute(0).second(0)
    time3.value = dayjs().hour(14).minute(30).second(59)
    time4.value = dayjs().hour(18).minute(30).second(0)
  }
}

//当前时间
const currentTime = ref(dayjs())
// const currentTime = ref(dayjs('2025-06-4 3:31:00'))
const emits = defineEmits(['showSuccessFn', 'updateAttendance'])
const showSuccessFn = () => {
  emits('showSuccessFn', true)
}
const updateAttendance = () => {
  emits('updateAttendance')
}

//控制显示"未开始"
const showTimeSlot1 = ref(false)
const showTimeSlot2 = ref(false)
const showTimeSlot3 = ref(false)
const showTimeSlot4 = ref(false)

const current = ref(0)

const profile = ref({})
const morningList1 = ref({})
const morningList2 = ref({})
const afternoonList1 = ref({})
const afternoonList2 = ref({})

onMounted(async () => {
  profile.value = (await getUserProfile()).data
  deptAttendabceZhenZhou.value = profile.value.deptId
  userIdAttendabce.value = profile.value.userId // 用户
  timeFn()
  //首先根据时间进行判断
  if (props.renCalendarCurDate) {
    if (
      dayjs().startOf('day') < props.renCalendarCurDate &&
      props.renCalendarCurDate <= time1.value
    ) {
      current.value = 0
      showTimeSlot1.value = true
      showTimeSlot2.value = false
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    }  else if (
      time1.value < currentTime.value &&
      currentTime.value <= time2.value &&
      Object.keys(morningList1.value).length === 0
    ) {
      current.value = 0
      showTimeSlot1.value = true
      showTimeSlot2.value = false
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    } else if (
      time1.value < currentTime.value &&
      currentTime.value <= time2.value &&
      Object.keys(morningList1.value).length !== 0
    ) {
      current.value = 1
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    } else if (
      time2.value < currentTime.value &&
      currentTime.value <= dayjs().hour(13).minute(15).second(0) &&
      Object.keys(morningList2.value).length === 0
    ) {
      current.value = 1
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    } else if (
      dayjs().hour(13).minute(15).second(0) < currentTime.value &&
      currentTime.value <= time3.value
    ) {
      current.value = 2
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = false
    } else if (
      time3.value < currentTime.value &&
      currentTime.value <= time4.value &&
      Object.keys(afternoonList1.value).length === 0
    ) {
      // 下午上班打卡显示
      current.value = 3

      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = false
    } else if (
      time3.value < currentTime.value &&
      currentTime.value <= time4.value &&
      Object.keys(afternoonList1.value).length > 0
    ) {
      // 下午上班打卡显示
      current.value = 3
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = true
    } else if (
      time4.value < currentTime.value &&
      currentTime.value < dayjs().endOf('day')
    ) {

      // 下午下班打卡显示
      current.value = 3
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = true
    }
  } else {
    if (
      dayjs().startOf('day') < currentTime.value &&
      currentTime.value <= time1.value
    ) {
      current.value = 0
      showTimeSlot1.value = true
      showTimeSlot2.value = false
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    } else if (
      time1.value < currentTime.value &&
      currentTime.value <= time2.value &&
      Object.keys(morningList1.value).length === 0
    ) {
      current.value = 0
      showTimeSlot1.value = true
      showTimeSlot2.value = false
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    } else if (
      time1.value < currentTime.value &&
      currentTime.value <= time2.value &&
      Object.keys(morningList1.value).length !== 0
    ) {
      current.value = 1
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    } else if (
      time2.value < currentTime.value &&
      currentTime.value <= dayjs().hour(13).minute(15).second(0) &&
      Object.keys(morningList2.value).length === 0
    ) {
      current.value = 1
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = false
      showTimeSlot4.value = false
    } else if (
      dayjs().hour(13).minute(15).second(0) < currentTime.value &&
      currentTime.value <= time3.value
    ) {
      current.value = 2
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = false
    } else if (
      time3.value < currentTime.value &&
      currentTime.value <= time4.value &&
      Object.keys(afternoonList1.value).length === 0
    ) {
      // 下午上班打卡显示
      current.value = 3

      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = false
    } else if (
      time3.value < currentTime.value &&
      currentTime.value <= time4.value &&
      Object.keys(afternoonList1.value).length > 0
    ) {
      // 下午上班打卡显示
      current.value = 3
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = true
    } else if (
      time4.value < currentTime.value &&
      currentTime.value < dayjs().endOf('day')
    ) {

      // 下午下班打卡显示
      current.value = 3
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = true
    }
  }
})

watch(
  () => props.renCalendarCurDate,
  async (val) => {
    if (val) {
      const params = {
        userId: null,
        deptId: null,
        punchTimeLte: new dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        punchTimeGte: new dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      }
      if (props.userInfo) {
        params.userId = props.userInfo.userId
        params.deptId = props.userInfo.deptId
        params.punchTimeLte = dayjs(val).format('YYYY-MM-DD 00:00:00')
        params.punchTimeGte = dayjs(val).format('YYYY-MM-DD 23:59:59')
      } else {
        profile.value = (await getUserProfile()).data
        params.userId = profile.value.userId
        params.deptId = profile.value.deptId
      }
      attendanceRecordList.value = (await getAttendanceRecordList(params)).rows
      morningList1.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '上午上班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}

      morningList2.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '上午下班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}

      afternoonList1.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '下午上班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}

      afternoonList2.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '下午下班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}
      showTimeSlot1.value = true
      showTimeSlot2.value = true
      showTimeSlot3.value = true
      showTimeSlot4.value = true
    } else {
      const params = {
        userId: null,
        deptId: null,
        punchTimeLte: new dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        punchTimeGte: new dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      }
      if (props.userInfo) {
        params.userId = props.userInfo.userId
        params.deptId = props.userInfo.deptId
        params.punchTimeLte = dayjs().format('YYYY-MM-DD 00:00:00')
        params.punchTimeGte = dayjs().format('YYYY-MM-DD 23:59:59')
      } else {
        profile.value = (await getUserProfile()).data
        params.userId = profile.value.userId
        params.deptId = profile.value.deptId
      }
      attendanceRecordList.value = (await getAttendanceRecordList(params)).rows
      morningList1.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '上午上班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}
      morningList2.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '上午下班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}
      afternoonList1.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '下午上班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}

      afternoonList2.value =
        attendanceRecordList.value
          .filter(
            (item) =>
              dayjs(val).isSame(item.punchTime, 'day') && // 确保是同一天
              item.punchType === '下午下班',
          )
          .reduce((latest, current) => {
            // 用 reduce 对比时间，保留最新的项
            if (!latest) return current
            return dayjs(current.punchTime).isAfter(latest.punchTime) ? current : latest
          }, null) || {}
    }
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <view class="containerClass">
    <uv-steps
      :current="current"
      active-color="#165DFF"
      direction="column"
      dot
      inactive-color="#86909C"
    >
      <uv-steps-item>
        <template v-slot:title>
          <text class="titleClass">应上班卡 {{ time1?.format('HH:mm') }}</text>
        </template>
        <template v-slot:desc>
          <SmallCard v-if="!showTimeSlot1" :content="'未开始'" />
          <view v-else>
            <SmallCard
              v-if="Object.keys(morningList1).length > 0"
              :content="morningList1?.type === '缺卡' ? '缺卡' : '已打卡'"
              :description="''"
              :punchEdit="false"
              :punchTime="
                morningList1?.type === '缺卡' ? '' : dayjs(morningList1.punchTime).format('HH:mm')
              "
              :type="morningList1?.type"
            />
            <ClockBox
              v-else-if="
                Object.keys(morningList1).length === 0 && showTimeSlot2 === false && !props.userInfo
              "
              :deptId="profile.deptId"
              :punchType="'上午上班'"
              :userId="profile.userId"
              @openSuccessView="$emit('openSuccessView')"
              @showSuccessFn="showSuccessFn"
            />
            <SmallCard
              v-else
              :content="'未打卡'"
              :description="''"
              :show-update-button="true"
              :type="'缺卡'"
            />
          </view>
        </template>
      </uv-steps-item>
      <uv-steps-item>
        <template v-slot:title>
          <text class="titleClass">应下班卡 {{ time2?.format('HH:mm') }}</text>
        </template>
        <template v-slot:desc>
          <SmallCard v-if="!showTimeSlot2" :content="'未开始'" />
          <view v-else>
            <SmallCard
              v-if="Object.keys(morningList2).length > 0"
              :content="morningList2?.type === '缺卡' ? '缺卡' : '已打卡'"
              :description="''"
              :punchEdit="false"
              :punchTime="
                morningList2?.type === '缺卡' ? '' : dayjs(morningList2.punchTime).format('HH:mm')
              "
              :show-update-button="true"
              :type="morningList2.type"
              :updateParams="{
                recordId: morningList2.recordId,
                userId: profile.userId,
                deptId: profile.deptId,
                punchType: '上午下班'
              }"
              @updateAttendance="updateAttendance"
            />
            <ClockBox
              v-else-if="
                Object.keys(morningList2).length === 0 && showTimeSlot3 === false && !props.userInfo
              "
              :deptId="profile.deptId"
              :punchType="'上午下班'"
              :userId="profile.userId"
              @openSuccessView="$emit('openSuccessView')"
              @showSuccessFn="showSuccessFn"
            />
            <SmallCard
              v-else
              :content="'未打卡'"
              :description="''"
              :show-update-button="true"
              :type="'缺卡'"
            />
          </view>
        </template>
      </uv-steps-item>
      <uv-steps-item>
        <template v-slot:title>
          <text class="titleClass">应上班卡 {{ time3?.format('HH:mm') }}</text>
        </template>
        <template v-slot:desc>
          <SmallCard v-if="!showTimeSlot3" :content="'未开始'" />
          <view v-else>
            <SmallCard
              v-if="Object.keys(afternoonList1).length > 0"
              :content="afternoonList1?.type == '缺卡' ? '缺卡' : '已打卡'"
              :description="''"
              :punchEdit="false"
              :punchTime="
                afternoonList1?.type === '缺卡'
                  ? ''
                  : dayjs(afternoonList1.punchTime).format('HH:mm')
              "
              :type="afternoonList1.type"
            />
            <ClockBox
              v-else-if="
                Object.keys(afternoonList1).length === 0 &&
                showTimeSlot4 === false &&
                !props.userInfo
              "
              :deptId="profile.deptId"
              :punchType="'下午上班'"
              :userId="profile.userId"
              @openSuccessView="$emit('openSuccessView')"
              @showSuccessFn="showSuccessFn"
            />
            <SmallCard
              v-else
              :content="'未打卡'"
              :description="''"
              :show-update-button="true"
              :type="'缺卡'"
            />
          </view>
        </template>
      </uv-steps-item>
      <uv-steps-item>
        <template v-slot:title>
          <text class="titleClass">应下班卡 {{ time4?.format('HH:mm') }}</text>
        </template>
        <template v-slot:desc>
          <SmallCard v-if="!showTimeSlot4" :content="'未开始'" />
          <view v-else>
            <SmallCard
              v-if="Object.keys(afternoonList2).length > 0"
              :content="afternoonList2?.type === '缺卡' ? '缺卡' : '已打卡'"
              :description="''"
              :punchEdit="true"
              :punchTime="
                afternoonList2?.type === '缺卡'
                  ? ''
                  : dayjs(afternoonList2.punchTime).format('HH:mm')
              "
              :show-update-button="true"
              :type="afternoonList2.type"
              :updateParams="{
                recordId: afternoonList2.recordId,
                userId: profile.userId,
                deptId: profile.deptId,
                punchType: '下午下班'
              }"
              @updateAttendance="updateAttendance"
            />
            <ClockBox
              v-else-if="Object.keys(afternoonList2).length === 0 && !props.userInfo"
              :deptId="profile.deptId"
              :punchType="'下午下班'"
              :userId="profile.userId"
              @openSuccessView="$emit('openSuccessView')"
              @showSuccessFn="showSuccessFn"
            />

            <SmallCard
              v-else
              :content="'未打卡'"
              :description="''"
              :show-update-button="true"
              :type="'缺卡'"
            />
          </view>
        </template>
      </uv-steps-item>
    </uv-steps>
  </view>
</template>
<style lang="scss" scoped>
@import '@/static/style/index.scss';

.containerClass {
  margin: 40rpx 20rpx;
}

.titleClass {
  align-self: stretch;
  color: #86909c;
  font-size: 28rpx;
  font-style: normal;
  font-weight: 400;
  line-height: 39.2rpx;
}

:deep(.uv-steps-item--column) {
  .uv-steps-item__wrapper--column--dot {
    background-color: $uni-bai;
  }
}

:deep(.uv-steps-item__content) {
  margin-left: 24rpx !important;
}

:deep(.uv-steps-item__line) {
  height: 100% !important;
}
</style>
